/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.server;

import com.google.inject.Inject;
import com.google.orkut.client.api.samples.greetings.server.db.ConfigEntry;
import com.google.orkut.client.api.samples.greetings.server.db.Utils;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

/**
 * Cached configuration of the site.
 *
 * @author Shishir Birmiwal
 */
public class CachedConfig {
  private static ConfigEntry config;
  private final PersistenceManagerFactory pmf;
  public static final long CONFIG_ID = 1;

  @Inject
  public CachedConfig(PersistenceManagerFactory pmf) {
    this.pmf = pmf;
  }

  public synchronized ConfigEntry getConfig() {
    if (config == null) {
      config = readConfig();
    }
    return config;
  }

  public void storeConfig(ConfigEntry config) {
    PersistenceManager pm = pmf.getPersistenceManager();
    ConfigEntry entry = Utils.copyOf(config);
    try {
      pm.makePersistent(entry);
      config = Utils.copyOf(entry);
    } catch (Exception ex) {
      // entry not present / accessible
      throw new RuntimeException(ex);
    } finally {
      pm.close();
    }
  }

  private ConfigEntry readConfig() {
    PersistenceManager pm = pmf.getPersistenceManager();
    try {
      ConfigEntry e = pm.getObjectById(ConfigEntry.class, CONFIG_ID);
      return Utils.copyOf(e);
    } catch (Exception e) {
      // entry not present / accessible
      return null;
    } finally {
      pm.close();
    }
  }
}
